import type { ProColumns } from '@ant-design/pro-components';
import { ModalForm, ProFormDatePicker, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import type { SaveProgrammeBookData } from '@fill/client';
import { queryClient, rspc } from '@fill/client';
import { Button, Card, Col, Form, Row, Space, Tabs, notification } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import type { HANDLE_APPROVAL_TYPE, HANDLE_STATUS_TYPE } from '../../constants/default';
import { APPROVAL_STATE, HANDLE_STATUS, NODE_TYPE, QUESTION_ENUM, STATUS_VALUE } from '../../constants/default';
import { checkStateUpdate } from '../../util/state';
import type { OpinionSchema } from '../opinion/interface';
import { Records } from '../rectification/Records';

export const OpinionBase = ({ readonly }: { readonly: boolean }) => {
  return (
    <Card title="问题基本信息">
      <ProFormSelect readonly={readonly} name="slug" label="问题分类" valueEnum={QUESTION_ENUM} />
      <ProFormText readonly={readonly} name="description" label="问题方面" />
      <ProFormTextArea readonly={readonly} name="content" label="具体问题" />
      <ProFormText readonly={readonly} name="remark" label="备注" />
    </Card>
  );
};

export const rectificationStatus = ['接受意见并整改', '无法整改'];
export const rectificationStatuOptions: {
  [key: number]: {
    text: string
  }
} = {};

rectificationStatus.map((text, index) => rectificationStatuOptions[index] = {
  text,
});

export const OpinionProgramme = ({ readonly = false, required = true }: { readonly?: boolean; required?: boolean }) => {
  return (
    <Card title="整改方案">
      <Row>
        <Col span={12}>
          <ProFormText readonly={readonly} label="责任部门" name={['programme_book', 'department']} labelCol={{
            span: 6,
          }} rules={[
            {
              required,
              message: '请输入责任部门',
            },
          ]} />
        </Col>
        <Col span={12}>
          <ProFormText readonly={readonly} label="责任领导" name={['programme_book', 'leader']} labelCol={{
            span: 6,
          }} rules={[
            {
              required,
              message: '请输入责任领导',
            },
          ]} />
        </Col>
        <Col span={12}>
          <ProFormText readonly={readonly} label="直接责任人" name={['programme_book', 'user']} labelCol={{
            span: 6,
          }} rules={[
            {
              required,
              message: '请输入直接责任人',
            },
          ]} />
        </Col>
        <Col span={12}>
          <ProFormDatePicker readonly={readonly} label="完成时限" name={['programme_book', 'completed_at']} width="md" labelCol={{
            span: 6,
          }} rules={[
            {
              required,
              message: '请输入完成时限',
            },
          ]} />
        </Col>
        <Col span={12}>
          <ProFormSelect readonly={readonly} label="是否整改" name={['programme_book', 'is_rectification']} labelCol={{
            span: 6,
          }} rules={[
            {
              required,
              message: '请选择是否整改',
            },
          ]} options={[
            { label: '接受意见并整改', value: '1' },
            { label: '无法整改', value: '2' },
          ]} />
        </Col>
        <Col span={24}>
          <ProFormTextArea readonly={readonly} label="巡察意见" name={['programme_book', 'proposal']} />
        </Col>
        <Col span={24}>
          <ProFormTextArea readonly={readonly} label="整改目标及具体措施" name={['programme_book', 'measures']} rules={[
            {
              required,
              message: '请输入整改目标及具体措施',
            },
          ]} />
        </Col>
      </Row>
    </Card>
  );
};

export const ProgrammeDetail = (records: OpinionSchema & { readonly: boolean; module: string }) => {
  const [form] = Form.useForm<any>();
  const { readonly, ...record } = records;
  const [open, setOpen] = useState(false);
  const saveProgrammeBook = rspc.useMutation('opnions.save_programme_book');

  useEffect(() => {
    form.setFieldsValue({
      ...record,
      programme_book: {
        ...record.programme_book,
        proposal: record.programme_book?.proposal?.replaceAll('<br />', '\n') || '',
        measures: record.programme_book?.measures?.replaceAll('<br />', '\n') || '',
      },
    });
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [record]);

  async function handleSubmit(tmp = false) {
    try {
      await form.validateFields();
    }
    catch (error) {
      return;
    }

    const { programme_book } = form.getFieldsValue();

    const _programme_book = {
      ...records.programme_book,
      ...programme_book,
    };

    const params: SaveProgrammeBookData = {
      uuid: record.uuid,
      department: _programme_book?.department || '',
      leader: _programme_book?.leader || '',
      user: _programme_book?.user || '',
      completed_at: (!!_programme_book?.completed_at && dayjs(_programme_book?.completed_at).format('YYYY-MM-DD HH:mm:ss')) || '',
      book_completed_at: (!!_programme_book?.book_completed_at && dayjs(_programme_book?.book_completed_at).format('YYYY-MM-DD HH:mm:ss')) || '',
      is_rectification: _programme_book?.is_rectification || '',
      proposal: (_programme_book?.proposal && _programme_book?.proposal.replaceAll('\n', '<br />')) || '',
      measures: (_programme_book?.measures && _programme_book?.measures.replaceAll('\n', '<br />')) || '',
      rectification_status: _programme_book?.rectification_status || '',
      completion_remark: _programme_book?.completion_remark || '',
      payment_found: _programme_book?.payment_found || '',
      other: _programme_book?.other || '',
      other_organization: _programme_book?.other_organization || '',
      investigation: _programme_book?.investigation || '',
      perfect: _programme_book?.perfect || '',
      status: tmp ? STATUS_VALUE.PENDING : STATUS_VALUE.PROCESSED,
      book_status: _programme_book?.book_status || '',
    };

    console.log(params, _programme_book);

    try {
      await saveProgrammeBook.mutateAsync({
        arg: params,
      }, {
        // onSuccess() {
        //   queryClient.refetchQueries({
        //     queryKey: ['opnions.get'],
        //   });
        // },
      });

      await queryClient.refetchQueries({
        queryKey: ['opnions.get'],
      });

      setOpen(false);
    }
    catch (error) {
      console.log(error);
      notification.error({
        message: '发生错误',
      });
    }
  }

  return (
    <>
      <a key="detail" onClick={() => setOpen(true)}>{readonly ? '查看' : '编辑'}</a>
      <ModalForm<OpinionSchema>
        width={1000}
        title="整改方案"
        // trigger={
        //   <a key="detail">{readonly ? '查看' : '编辑'}</a>
        // }
        layout="horizontal"
        labelCol={{
          span: 3,
        }}
        labelWrap={true}
        modalProps={{
          destroyOnClose: true,
        }}
        form={form}
        readonly={readonly}
        onOpenChange={(e) => {
          setOpen(e);
        }}
        submitter={{
          render() {
            return <div style={{
              display: 'flex',
              flex: 1,
              justifyContent: 'center',
            }}>
              {[
                !readonly && <Button type="primary" key="tmp" onClick={() => handleSubmit(true)}>暂存</Button>,
                !readonly && <Button type="primary" key="submit" onClick={() => handleSubmit()}>确定</Button>,
                <Button key="cancel" onClick={() => setOpen(false)}>取消</Button>,
              ]}
            </div>;
          },
        }}
        open={open}
        // initialValues={record}
        // onFinish={async ({ programme_book }) => {
        //   console.log({
        //     ...programme_book,
        //   });

        //   const _programme_book = {
        //     ...records.programme_book,
        //     ...programme_book,
        //   };

        //   try {
        //     const params: SaveProgrammeBookData = {
        //       uuid: record.uuid,
        //       department: _programme_book?.department || '',
        //       leader: _programme_book?.leader || '',
        //       user: _programme_book?.user || '',
        //       completed_at: (_programme_book?.completed_at && dayjs(_programme_book?.completed_at).format('YYYY-MM-DD HH:mm:ss')) || '',
        //       book_completed_at: (_programme_book?.completed_at && dayjs(_programme_book?.book_completed_at).format('YYYY-MM-DD HH:mm:ss')) || '',
        //       is_rectification: _programme_book?.is_rectification || '',
        //       proposal: _programme_book?.proposal || '',
        //       measures: _programme_book?.measures || '',
        //       rectification_status: _programme_book?.rectification_status || '',
        //       completion_remark: _programme_book?.completion_remark || '',
        //       payment_found: _programme_book?.payment_found || '',
        //       other: _programme_book?.other || '',
        //       other_organization: _programme_book?.other_organization || '',
        //       investigation: _programme_book?.investigation || '',
        //       perfect: _programme_book?.perfect || '',
        //       status: '2',
        //       book_status: _programme_book?.book_status || '',
        //     };

        //     console.log(params);

        //     await saveProgrammeBook.mutateAsync({
        //       arg: params,
        //     }, {
        //       onSuccess() {
        //         queryClient.refetchQueries({
        //           queryKey: ['opnions.get'],
        //         });
        //       },
        //     });

        //     return true;
        //   }
        //   catch (error) {
        //     return false;
        //   }
        // }}
      >
        {
          readonly
            ? (
            <Tabs defaultActiveKey="1" items={[
              {
                key: '1',
                label: '整改方案',
                children: <Space direction="vertical" style={{
                  display: 'flex',
                }}>
                  <OpinionBase readonly />
                  <OpinionProgramme required readonly={false} />
                </Space>,
              },
              {
                key: '2',
                label: '提交审批记录',
                children: <Records key="records" module={NODE_TYPE.PROGRAMME} relation_uuid={records.uuid} />,
              },
            ]} />
              )
            : (
                <>
                  <br />
                  <OpinionBase readonly />
                  <OpinionProgramme required readonly={false} />
                </>
              )
        }
      </ModalForm>
    </>
  );
};

export const useProgramme = () => {
  const [slugsData, setSlugsData] = useState<string[]>([]);

  const { data } = rspc.useQuery(['opnions.slugs', { arg: null }]);

  useEffect(
    () => {
      const _slugsData: string[] = [];

      data?.map(({ slug }) => _slugsData.push(slug));
      console.log(data);
      setSlugsData(_slugsData);
    },
    [data],
  );

  const columns: ProColumns<any>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '问题分类',
      dataIndex: 'slug',
      valueEnum: QUESTION_ENUM,
      width: 300,
    },
    {
      title: '问题方面',
      dataIndex: 'description',
      width: 250,
    },
    {
      title: '具体问题',
      dataIndex: 'content',
      width: 410,
    },
    {
      title: '完成时限',
      width: 160,
      render(_, { programme_book }) {
        return (<div>{(!!programme_book?.completed_at && dayjs(programme_book?.completed_at).format('YYYY-MM-DD')) || '-'}</div>);
      },
    },
    {
      title: '责任人',
      width: 140,
      render(_, { programme_book }) {
        return (<div>{programme_book?.user || '-'}</div>);
      },
    },
    {
      title: '审批状态',
      dataIndex: 'state',
      width: 120,
      render(_, { programme_book }) {
        return (
          <div>{(programme_book?.state && APPROVAL_STATE[programme_book.state as HANDLE_APPROVAL_TYPE]) || '-'}</div>
        );
      },
    },
    {
      title: '处理状态',
      dataIndex: 'status',
      width: 120,
      render(_, { programme_book }) {
        return (
          <div>{(programme_book?.status && HANDLE_STATUS[programme_book.status as HANDLE_STATUS_TYPE]) || '-'}</div>
        );
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      width: 140,
      render: (text, record) => [
        <ProgrammeDetail key="detail" {...record} readonly />,
        checkStateUpdate(record.programme_book?.state || '') && <ProgrammeDetail key="edit" {...record} />,
      ],
    },
  ];

  return {
    columns,
    slugsData,
  };
};
